package com.gosling.cloudspace.tools;

import cn.hutool.core.io.FileUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @author Administrator
 */
public class Pdf2PngUtil {

    public static final Logger logger = LoggerFactory.getLogger(Pdf2PngUtil.class);

    public static void pdf2Png(String pdfFilePath) {
        // 输出图像文件夹路径
        String outputImagePath = "C:\\Users\\EDY\\Desktop\\";
        try {
            // 加载PDF文档
            PDDocument document = PDDocument.load(new File(pdfFilePath));
            // 创建PDF渲染器
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            FileUtil.mkdir(outputImagePath);
            // 循环处理每一页
            for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) {
                // 渲染页面为BufferedImage
                BufferedImage bufferedImage = pdfRenderer.renderImage(pageIndex);
                // 设置输出图像文件名
                String outputImageName = "page_" + (pageIndex + 1) + ".png";
                // 输出图像文件路径
                String outputImageFilePath = outputImagePath + outputImageName;
                // 将BufferedImage写入到文件
                ImageIO.write(bufferedImage, "png", new File(outputImageFilePath));
            }
            // 关闭PDF文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public File regTableFill(RegProtocolFillDto dto) throws Exception {
//        File target = new File("//test");
//        //读pdf
//        PdfReader reader = new PdfReader(regProtocolUrl);
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        PdfStamper ps = new PdfStamper(reader, bos);
//        AcroFields s = ps.getAcroFields();
//        // 设置字体
//        ArrayList<BaseFont> fontList = new ArrayList<>();
//        BaseFont bf = BaseFont.createFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//        fontList.add(bf);
//        s.setSubstitutionFonts(fontList);
//        s.setField("merName", dto.getMerName());
//        s.setField("merAbbr", dto.getMerAbbr());
//        s.setField("registeredFund", dto.getRegisteredFund());
//        s.setField("registeredAddr", dto.getRegisteredAddr());
//        s.setField("businessLicenceNo", dto.getBusinessLicenceNo());
//        s.setField("businessLicencePeriod", dto.getBusinessLicencePeriod());
//        s.setField("businessScope", dto.getBusinessScope());
//        s.setField("openBank", dto.getOpenBank());
//        s.setGenerateAppearances(true);
//        ps.setFormFlattening(true);
//        ps.close();
//        FileOutputStream fos = new FileOutputStream(target);
//        fos.write(bos.toByteArray());
//        fos.close();
//        return target;
//    }
}